<?php
/**
 * @Description: 档案袋信息
 * @Author: kzj
 * @datetime: 2023-03-31
 */
namespace App\Services\Information;

use App\Models\BasicInfoAddress;
use App\Models\BasicInfoAnnualAssessment;
use App\Models\BasicInfoChange;
use App\Models\BasicInfoGraduatedSchool;
use App\Models\BasicInfoLearnHistory;
use App\Models\BasicInfoPosition;
use App\Models\BasicInfoWorkHistory;
use App\Models\BasicTitleInfo;
use App\Models\DictionaryItem;
use App\Models\System\Tasks;
use App\Models\System\Term;
use App\Models\Teachers;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

/**
 * 档案袋信息 (服务)
 */
class ArchivesService
{
    public function __construct()
    {

    }
    
    /**
     * @Description: 添加职务数据
     * @Author: kzj
     * @datetime: 2023-03-31
     */
    public function addPosition($request)
    {
        if(!$request['user_id']) {
            throw new \Exception('参数缺失！');
        }
        unset($request['id']);

        $user = Auth::user();
        $request['creator_id'] = $user->id;
        $term = Term::whereId($request['data_version_id'])->first();

        $termEndDate = Carbon::parse($term->end_date);
        $beginDate = Carbon::parse($request['begin_date']);
        $endDate = Carbon::parse($request['end_date']);
        if($endDate->gt($termEndDate)) {
            throw new \Exception('结束时间超过当前学期范围日期'. $termEndDate->toDateString());
        }
        if($beginDate->gt($endDate)) {
            throw new \Exception('开始时间不能超过结束时间');
        }

        $titleSet = DictionaryItem::select('item_order as order','id as optionId','parent_id as parentId','item_value as selectKey','item_name as selectValue')
            ->where('id', $request['title'])
            ->first();
            
        $request['title'] = json_encode([$titleSet->toArray()]);
        
        $result = BasicInfoPosition::create($request);

        return $result;
    }

    /**
     * @Description: 添加学习经历数据
     * @Author: kzj
     * @datetime: 2023-03-31
     */
    public function addLearnHistory($request)
    {
        if(!$request['user_id']) {
            throw new \Exception('参数缺失！');
        }
        unset($request['id']);

        $user = Auth::user();
        $request['creator_id'] = $user->id;
        
        $result = BasicInfoLearnHistory::create($request);

        return $result;
    }
    
    /**
     * @Description: 添加工作经历数据
     * @Author: kzj
     * @datetime: 2023-03-31
     */
    public function addWorkHistory($request)
    {
        if(!$request['user_id']) {
            throw new \Exception('参数缺失！');
        }
        unset($request['id']);

        $user = Auth::user();
        $request['creator_id'] = $user->id;
        
        $result = BasicInfoWorkHistory::create($request);

        return $result;
    }
    
    /**
     * @Description: 添加年度考核数据
     * @Author: kzj
     * @datetime: 2023-03-31
     */
    public function addAssessment($request)
    {
        if(!$request['user_id']) {
            throw new \Exception('参数缺失！');
        }
        unset($request['id']);
        
        $situationSet = DictionaryItem::select('item_order as order','id as optionId','parent_id as parentId','item_value as selectKey','item_name as selectValue')
            ->where('id', $request['situation'])
            ->first();
            
        $request['situation'] = json_encode([$situationSet->toArray()]);

        $user = Auth::user();
        $request['creator_id'] = $user->id;
        $endOfYear = Carbon::createFromDate($request['year'], 12, 31);

        $request['year'] = $endOfYear->toDateTimeString();
        $startOfYear = $endOfYear->firstOfYear()->toDateTimeString();
        
        $userAssess = BasicInfoAnnualAssessment::where('user_id', $request['user_id'])
            ->where('year', '>=', $startOfYear)
            ->where('year', '<=', $request['year'])
            ->first();
            
        if($userAssess) {
            throw new \Exception('该年度已有考核记录！');
            // $result = BasicInfoAnnualAssessment::where('id', $userAssess->id)->update($request);
        } else {
            $result = BasicInfoAnnualAssessment::create($request);
        }

        return $result;
    }
    
    /**
     * @Description: 编辑职务数据
     * @Author: kzj
     * @datetime: 2023-03-31
     */
    public function editPosition($request)
    {
        if(!$request['user_id'] || !$request['id']) {
            throw new \Exception('参数缺失！');
        }

        $user = Auth::user();
        $request['updater_id'] = $user->id;
        $term = Term::whereId($request['data_version_id'])->first();

        $termEndDate = Carbon::parse($term->end_date);
        $beginDate = Carbon::parse($request['begin_date']);
        $endDate = Carbon::parse($request['end_date']);
        if($endDate->gt($termEndDate)) {
            throw new \Exception('结束时间超过当前学期范围日期'. $termEndDate->toDateString());
        }
        if($beginDate->gt($endDate)) {
            throw new \Exception('开始时间不能超过结束时间');
        }

        $titleSet = DictionaryItem::select('item_order as order','id as optionId','parent_id as parentId','item_value as selectKey','item_name as selectValue')
            ->where('id', $request['title'])
            ->first();
            
        $request['title'] = json_encode([$titleSet->toArray()]);
        
        $result = BasicInfoPosition::whereId($request['id'])->update($request);

        return $result;
    }

    /**
     * @Description: 编辑学习经历数据
     * @Author: kzj
     * @datetime: 2023-03-31
     */
    public function editLearnHistory($request)
    {
        if(!$request['user_id'] || !$request['id']) {
            throw new \Exception('参数缺失！');
        }

        $user = Auth::user();
        $request['updater_id'] = $user->id;
        
        $result = BasicInfoLearnHistory::whereId($request['id'])->update($request);

        return $result;
    }

    /**
     * @Description: 编辑工作经历数据
     * @Author: kzj
     * @datetime: 2023-03-31
     */
    public function editWorkHistory($request)
    {
        if(!$request['user_id'] || !$request['id']) {
            throw new \Exception('参数缺失！');
        }

        $user = Auth::user();
        $request['updater_id'] = $user->id;
        
        $result = BasicInfoWorkHistory::whereId($request['id'])->update($request);

        return $result;
    }

    /**
     * @Description: 编辑年度考核数据
     * @Author: kzj
     * @datetime: 2023-03-31
     */
    public function editAssessment($request)
    {
        if(!$request['user_id'] || !$request['id']) {
            throw new \Exception('参数缺失！');
        }

        $situationSet = DictionaryItem::select('item_order as order','id as optionId','parent_id as parentId','item_value as selectKey','item_name as selectValue')
            ->where('id', $request['situation'])
            ->first();
            
        $request['situation'] = json_encode([$situationSet->toArray()]);

        $user = Auth::user();
        $request['updater_id'] = $user->id;
        $request['year'] = Carbon::createFromDate($request['year'], 12, 31);
        
        $result = BasicInfoAnnualAssessment::whereId($request['id'])->update($request);

        return $result;
    }
    
    /**
     * @Description: 删除职务数据
     * @Author: kzj
     * @datetime: 2023-03-31
     */
    public function delPosition($request)
    {
        if(!$request['id']) {
            throw new \Exception('参数缺失！');
        }
        
        $result = BasicInfoPosition::whereId($request['id'])->update(['deleted' => 1]);

        return $result;
    }

    /**
     * @Description: 删除学习经历数据
     * @Author: kzj
     * @datetime: 2023-03-31
     */
    public function delLearnHistory($request)
    {
        if(!$request['id']) {
            throw new \Exception('参数缺失！');
        }
        
        $result = BasicInfoLearnHistory::whereId($request['id'])->update(['deleted' => 1]);

        return $result;
    }

    /**
     * @Description: 删除工作经历数据
     * @Author: kzj
     * @datetime: 2023-03-31
     */
    public function delWorkHistory($request)
    {
        if(!$request['id']) {
            throw new \Exception('参数缺失！');
        }
        
        $result = BasicInfoWorkHistory::whereId($request['id'])->update(['deleted' => 1]);

        return $result;
    }

    /**
     * @Description: 删除年度考核数据
     * @Author: kzj
     * @datetime: 2023-03-31
     */
    public function delAssessment($request)
    {
        if(!$request['id']) {
            throw new \Exception('参数缺失！');
        }
        
        $result = BasicInfoAnnualAssessment::whereId($request['id'])->update(['deleted' => 1]);

        return $result;
    }


    /**
     * @Description: 审核基本信息数据
     * @Author: kzj
     * @datetime: 2023-03-31
     */
    public function getCheckInfo($request)
    {
        if(!$request['id']) {
            throw new \Exception('没有数据修改权限！');
        }

        $result = BasicInfoChange::whereId($request['id'])->first();

        return $result;
    }

    /**
     * @Description: 基本信息编辑提交
     * @Author: kzj
     * @datetime: 2023-03-31
     */
    public function subBasicInfo($request)
    {
        if(!$request['user_id']) {
            throw new \Exception('没有数据修改权限！');
        }

        $user = Auth::user();
        // dd($request,$user->is_checker,is_check(309));
        
        $toCheck = false;
        $isAdmin = true;
        try{   
            DB::beginTransaction();
            // 支持管理员修改所有教师信息，修改后不需要审核
            if($user->is_checker) {
                unset($request['iszc']);
                $this->doUpdateInfo((object) $request);
            } else {
                $isAdmin = false;
                if(in_array($request['field'], ['tea_title', 'tea_gain_time', 'tea_title_rank', 'tea_employ_time', 'manage_title', 'manage_gain_time', 'manage_title_rank', 'manage_employ_time'])) {
                    if(is_check(309)){
                        //todo 直接更新数据
                        unset($request['iszc']);
                        $this->doUpdateInfo((object) $request);
                    //     return true;
                    } else {
                        throw new \Exception('没有数据修改权限！');
                    }
                } else {
                    if($user->id != $request['user_id']) {
                        throw new \Exception('没有数据修改权限！');
                    } else {
                        unset($request['iszc']);
                        // 教师资格证号、师训号、开始工作时间（其他信息修改后不需要审核）
                        if(in_array($request['field'], ['teacher_certificate_no', 'teacher_no', 'work_date'])) {
                            $toCheck = true;
                        } else {
                            $this->doUpdateInfo((object) $request);
                        }
                    }
                }
            }
            // dd($toCheck);
            $request['origin_value'] = $request['origin_value'] ?? "";
            $request['status'] = $toCheck ? 0 : 3;

            $request['change_value'] = $request['change_value'] ?? "";
            $request['update_value'] = $request['update_value'] ?? "";
            $changeInfo = BasicInfoChange::create($request);

            if($toCheck) {
                $optName = $request['type'] == 1 ? "新增" : "更新";            
                Tasks::create([
                    'name' => '【基本信息更新】审核' . $user->nickname . $optName . $request['field_name'],
                    'form_id' => $changeInfo->id,
                    'form_key' => 'BASIC_INFO_CHANGE',
                    'start_date' => date('Y-m-d H:i:s'),
                    'end_date' => date('Y-m-d H:i:s'),
                    'type' => 1,
                    'creator_id' => $user->id,
                    'creator_name' => $user->nickname,
                    'param' => '?user_id=' . $user->id . '&check_id=' . $changeInfo->id,
                    'url'=>'/information/archives/check',
                    'menu_id'=> 307
                ]);
            }

            DB::commit();
        }catch(\Exception $e){
            DB::rollback();
            throw new \Exception($e->getMessage());
        }

        $result = [
            'is_admin' => $isAdmin,
            'to_check' => $toCheck,
            'change_info' => $changeInfo
        ];

        return $result;
    }


    /**
     * @Description: 基本信息编辑审核提交
     * @Author: kzj
     * @datetime: 2023-03-31
     */
    public function subCheckBasicInfo($request)
    {
        if(!$request['id']) {
            throw new \Exception('参数缺失');
        }
        if(!$request['status']) {
            throw new \Exception('审核结果不能为空！');
        }

        $user = Auth::user();
        unset($request['content']);
        
        try{   
            DB::beginTransaction();
            
            if($request['status'] == 1) {
                $changeInfo = BasicInfoChange::whereId($request['id'])->first();
                $this->doUpdateInfo($changeInfo);
            }

            //修改待办事项
            Tasks::where('form_key','BASIC_INFO_CHANGE')->where('form_id', $request['id'])->update(['status' => 2]);

            $result = BasicInfoChange::whereId($request['id'])->update($request);

            DB::commit();
        }catch(\Exception $e){
            DB::rollback();
            throw new \Exception($e->getMessage());
        }

        return $result;
    }

    
    /**
     * @Description: 更新教师信息
     * @Author: kzj
     * @datetime: 2023-03-31
     */
    public function doUpdateInfo($info)
    {
        if($info->data_type == 2) {
            $dicData = DictionaryItem::select('item_order as order','id as optionId','parent_id as parentId','item_value as selectKey','item_name as selectValue')
                ->where('id', $info->update_value)
                ->first();

            switch($info->field) {
                case 'gender':
                case 'nation':
                case 'political':
                case 'major_subject':
                    Teachers::where('user_id', $info->user_id)->where('deleted', 0)->update([$info->field => json_encode([$dicData->toArray()])]);
                    break;
                case 'academic':
                case 'degree':
                    BasicInfoGraduatedSchool::updateOrCreate([
                        'user_id' => $info->user_id, 
                        'deleted' => 0
                    ],[$info->field => json_encode([$dicData->toArray()])]);
                    break;
                case 'tea_title':
                case 'tea_title_rank':
                case 'manage_title':
                case 'manage_title_rank':
                    BasicTitleInfo::updateOrCreate([
                        'user_id' => $info->user_id, 
                        'deleted' => 0
                    ],[$info->field => json_encode([$dicData->toArray()])]);
                    break;
            }
        } else if($info->data_type == 4) {
            $cityData = DictionaryItem::select('item_order as order','id as optionId','parent_id as parentId','item_value as selectKey','item_name as selectValue')
                ->where('id', $info->update_value)
                ->first();

            $provinceData = DictionaryItem::select('item_order as order','id as optionId','parent_id as parentId','item_value as selectKey','item_name as selectValue')
                ->where('id', $cityData->parentId)
                ->first();
                
            $addressData = [
                "province" => $provinceData->toArray(),
                "city" => $cityData->toArray()
            ];
            
            switch($info->field) {
                case 'native_place':
                    Teachers::where('user_id', $info->user_id)->where('deleted', 0)->update([$info->field => json_encode([$addressData])]);
                    break; 
                case 'census_city':
                case 'home_city': 
                    BasicInfoAddress::updateOrCreate([
                        'user_id' => $info->user_id, 
                        'deleted' => 0
                    ],[$info->field => json_encode([$addressData])]);
                    break;       
            }
        } else {
            switch($info->field) {
                case 'name':
                case 'id_no':
                case 'mobile':
                case 'phone_num':
                case 'teacher_certificate_no':
                case 'teacher_no':
                case 'birthday':
                case 'join_date':
                case 'work_date':
                case 'teaching_date':
                case 'unit_date':
                    Teachers::where('user_id', $info->user_id)->where('deleted', 0)->update([$info->field => $info->update_value]);
                    break;
                case 'graduated_school':
                case 'graduated_date':
                    BasicInfoGraduatedSchool::updateOrCreate([
                        'user_id' => $info->user_id, 
                        'deleted' => 0
                    ],[$info->field => $info->update_value]);
                    break;
                case 'census_postcode':
                case 'census_address':
                case 'home_postcode':
                case 'home_address':
                    BasicInfoAddress::updateOrCreate([
                        'user_id' => $info->user_id, 
                        'deleted' => 0
                    ],[$info->field => $info->update_value]);
                    break;
                case 'tea_gain_time':
                case 'tea_employ_time':
                case 'manage_gain_time':
                case 'manage_employ_time':
                    BasicTitleInfo::updateOrCreate([
                        'user_id' => $info->user_id, 
                        'deleted' => 0
                    ],[$info->field => $info->update_value]);
                    break;       
            }
        }
    }
    
}